package com.yhg.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.yhg.Order.Bean.Order;
import com.yhg.Service.OrderService;
import com.yhg.properties.OrderProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
//@RequestMapping("/api/order")  //增加路径前缀
//@RefreshScope //支持实时刷新
public class OrderController {

    @Autowired
    OrderService orderService;

//    @Value("${order.timeout}")
//    String orderTimeout;
//    @Value("${order.auto-confirm}")
//    String orderAutoconfirm;
    @Autowired
    OrderProperties orderProperties;
    @GetMapping("/config")
    public String config(){
        return "order.timeout="+orderProperties.getTimeout()+",order.auto-confirm="+orderProperties.getAutoConfirm()+orderProperties.getDbUrl();
    }

    //创建订单
    @GetMapping("/create")
    public Order createOrder(@RequestParam("userId") Long userId,
                             @RequestParam("productId") Long productId){
        Order order = orderService.createOrder(productId,userId);
        return order;
    }

    /*
    功能：秒杀
    学习内容：服务保护---热点规则（精确到参数级别的限流）

    fallback的异常处理范围比block大：（1）所以 fallback搭配Throwable（2）blockhandler搭配BlockException
     */
    @GetMapping("/seckill")
    @SentinelResource(value = "seckill",fallback = "seckillFallback")
    public Order seckill(@RequestParam("userId") Long userId,
                        @RequestParam("productId") Long productId){
        Order order = orderService.createOrder(productId,userId);
        order.setId(Long.MAX_VALUE);
        return order;
    }

    public Order seckillFallback(Long userId, Long productId, Throwable ex){
        System.out.println("秒杀兜底回调方法");
        Order order = new Order();
        order.setId(productId);

        order.setUserId(userId);
        order.setAddress("异常信息"+ex.getClass());
        return order;
    }

    @GetMapping("/readDB")
    public String readDB(){
        System.out.println("读取数据库");
        return "success";
    }
}
